;(function(){
    "use strict"
    const osubmit = document.getElementById("submit");
    const otel = document.getElementById("login_id");
    const opassword = document.getElementById("password");
    
    osubmit.onclick = function(){
        ajax("http://localhost:3000/api",function(res){
            res = JSON.parse(res);
    
            if(res.code === 0){
                alert("用户名不存在，请先注册");
                location.href = "./regist.html";
            }else if(res.code === 1){
                // 登录成功之后，将登录成功信息，存到本地存储，方便其他功能或页面使用
                // 登陆状态
                localStorage.setItem("isLogin","ok");
                // 用户名
                localStorage.setItem("username",res.data);
    
                if(confirm("登录成功，是否跳转到首页")){
                    location.href = "./index.html";
                }
            }else if(res.code === 2){
                alert("密码不符，请重新输入");
                opassword.value = "";
                opassword.focus();
            }
        },{
            type:"login",
            username:otel.value,
            password:opassword.value
        })
    }
    
    
    function ajax(url, callback, data){
        let str = "";
        for(let i in data){
            str += `${i}=${data[i]}&`
        }
        url += "?" + str;
        const xhr = new XMLHttpRequest();
        xhr.open("get",url)
        xhr.onload = function(){
            if(xhr.status === 200){
                callback(xhr.responseText)
            }
        }
        xhr.send();
    }
    

})();    

